<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose" width="1000"
    :close-on-click-modal="false">
    <div class="fr">
      <el-form :inline="true" :model="formInline" size="small">
        <el-form-item label="类型" prop="type">
          <el-select v-model="formInline.type" style="width: 100%;">
            <el-option v-for="(item, index) in typeDatas" :key="'temper' + index" :label="item"
              :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="名称" prop="name" v-if="formInline.type">
            <el-select v-model="formInline.name" style="width: 100%;">
                <el-option v-for="(item,index) in nameDatas" :key="'temper'+index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
          <!-- <el-button type="primary" plain @click="handleReset" size="small" >重置</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <el-table v-loading="loading" :data="tableData" height="300px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column label="序号" type="index" width="50" :index="indexMethod"></el-table-column>
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="meterialName" label="被连接件材料"></el-table-column>
      <el-table-column prop="meterialMM" label="被连接件厚度(mm)"></el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button type="text" @click="editRow(scope.row, 'meterial')">选择被连接件材料</el-button>
          <el-button type="text" @click="editRow(scope.row, 'thinkness')">填写被连接件厚度</el-button>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="handleClose">取 消</el-button>
      <el-button size="mini" type="primary" @click="handleConfirm">确 定</el-button>
    </span>
    <FastenerMeterial ref="fastenerMeterialRef" :type="dialogType" @on-close="close" />
  </el-dialog>
</template>

<script>
import { v4 as uuid } from 'uuid';
import tinymce from "tinymce/tinymce";
import { getFastenerCategory, getFastenerQueryOption, queryFasteners } from '@/api/materialLibrary.js';
import { saveVeriableValue } from '@/api/computingConfig.js';
import FastenerMeterial from './FastenerMeterial.vue';
export default {
  name: "ProvisionRepalceDialog",
  components: {
    FastenerMeterial
  },
  data() {
    return {
      title: '选择紧固件',
      dialogVisible: false,
      fastenerVisiable: false,
      formInline: {
        type: ''
      },
      typeDatas: [],
      nameDatas: [],
      loading: false,
      datas: {},
      tableData: [],
      multipleSelection: [],
      fields: [],
      currentData: null,
      dialogType: 'meterial'
    };
  },
  mounted() {
    this.initData()
  },
  methods: {
    async close(data) {
      this.fastenerVisiable = false;
      if (data) {
        if (this.dialogType == 'meterial') {
          await this.tableData.forEach(item => {
            if (item.name == this.currentData.name) {
              item.meterialName = data?.data?.series;
            }
          })
        } else {
          await this.tableData.forEach(item => {
            if (item.name == this.currentData.name) {
              item.meterialMM = data?.data;
            }
          })
        }

        this.$forceUpdate();
      }
    },
    editRow(data, type) {
      this.currentData = data;
      this.dialogType = type;
      this.fastenerVisiable = true;
      this.$refs.fastenerMeterialRef.show();
    },
    show() {
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    async handleConfirm() {
      if (!this.multipleSelection.length) {
        return this.$message.warning('请选择数据！')
      }
      await this.getDatas()
      // this.$store.commit('xmleditor/SET_PROVISION_SELECTIONS', this.multipleSelection)
      const tableTitles = this.datas.titles
      const tableAttrs = this.datas.columns
      const tableDatas = this.datas.data.map((item, index) => {
        item.index = index + 1
        return item
      })
      // 添加新字段
      tableTitles.splice(2,1)
      tableAttrs.splice(2,1)
      tableTitles.push("被连接件材料")
      tableTitles.push("被连接件厚度(mm)")
      tableAttrs.push('meterialName')
      tableAttrs.push('meterialMM')
      await this.datas.data.forEach(async(item)=>{
        await this.multipleSelection.forEach(el=>{
          if(el.name == item.name){
            item.meterialName = el.meterialName;
            item.meterialMM = el.meterialMM;
          }
        })
      })
      const tableId = this.$store.state.xmleditor.variableTableDataId;
      if (tableId?.dataId) {
        const doc = tinymce.activeEditor.getDoc();
        const nodes = doc.querySelector(`[data-id="${tableId?.dataId}"]`)
        const tableChildren = nodes.childNodes;
        tableChildren.forEach(el => {
          if (el.nodeName == 'CAPTION') {
            this.caption = el.innerHTML;
          }
          // 表头设置
          if (el.nodeName == 'THEAD') {
            let tr = '';
            if (tableTitles.length > 0) {
              tableTitles.forEach(title => {
                let th = '';
                th = `<th colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${title}​</p>
	                    </th>`
                tr += th;
              })
              tr = `<tr data-id="${uuid()}">${tr}</tr>`
            }
            el.innerHTML = tr
          }
          // 数据设置
          if (el.nodeName == 'TBODY') {
            let tbody = '';
            if (tableDatas.length > 0) {
              tableDatas.forEach((dataItem, index) => {
                let tr = '';
                tableAttrs.forEach(tdData => {
                  let td = '';
                  td = `<td colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${dataItem[tdData] || ''}​</p>
	                    </td>`
                  tr += td;
                })
                tbody += `<tr data-id="${uuid()}">${tr}</tr>`
              })

            }
            el.innerHTML = tbody
          }
        })
      }
      // 保存变量值
      const variableContent = {
        columns: tableAttrs,
        titles: tableTitles,
        data: this.tableData
      }
      const formData = new FormData();
      formData.append("docNo", this.$store.state.xmleditor.docInfo.docNo);
      formData.append("id", Number.parseInt(tableId?.variableId));
      formData.append("variableContent", JSON.stringify(variableContent));
      saveVeriableValue(formData)
      this.dialogVisible = false;
    },
    indexMethod(index) {
      return (
        index + 1
      );
    },
    initData() {
      getFastenerCategory().then(res => {
        this.typeDatas = res.data.type
        this.formInline.type = this.typeDatas[0];
        this.handleSearch();
      })
    },
    handleSearch() {
      const obj = {
        type: this.formInline.type
      }
      getFastenerQueryOption(obj).then(res => {
        const newData = res.data
        this.tableData = newData.name.map(item => {
          return {
            name: item,
            meterialName: '',
            meterialMM: ''
          }
        })
      })
    },
    async getDatas() {
      const obj = {
        type: this.formInline.type,
        names: this.multipleSelection.map(item => item.name)
      }
      const res = await queryFasteners(obj)
      this.datas = res.data
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style scoped></style>